# -*-coding:utf-8-*-
import json
import pandas as pd
import numpy as np
import redis
import time
import requests
import sys
from datetime import datetime
from websocket import create_connection
from loguru import logger

pool = redis.ConnectionPool(host='localhost',
                            port=6379,
                            decode_responses=True,
                            db=0)
r = redis.Redis(connection_pool=pool)

symbol = sys.argv[1]
symbol = symbol.lower()

max_len = 10000

the_key = f'{symbol}_trade'
r.delete(the_key)

ws = create_connection(f"wss://stream.binance.com:9443/ws/{symbol}@trade")

last_trim = time.time()
while True:
    data = ws.recv()
    data = json.loads(data)
    data.pop('e', '没有这个键')
    data.pop('s', '没有这个键')
    data.pop('t', '没有这个键')
    data.pop('b', '没有这个键')
    data.pop('T', '没有这个键')
    data.pop('M', '没有这个键')
    E = data['E']
    ts = E / 1000
    t = datetime.fromtimestamp(ts)
    str_t = datetime.strftime(t, '%Y-%m-%d %H:%M:%S.%f')
    data.update({'t': str_t})
    data.pop('E', '没有这个键')

    data = json.dumps(data)
    r.lpush(the_key, data)

    # 每一分钟修剪一次redis数组
    if time.time() - last_trim > 60:
        r.ltrim(the_key, 0, max_len)
        last_trim = time.time()
        logger.info(f'length:{len(r.lrange(the_key, 0, -1))}')
